package com.example.result.explore

import android.content.ComponentName
import android.content.Context.BIND_AUTO_CREATE
import android.content.Intent
import android.content.ServiceConnection
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalView
import com.example.result.MessengerServer
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first

var p by mutableStateOf("")
var handler = object : Handler(Looper.myLooper()!!) {
    override fun handleMessage(msg: Message) {
        when (msg.what) {
            MessengerServer.MSG_TO -> {
                p += "\n"
                p += msg.obj
            }
        }
    }
}

@Composable
fun ProcessCommunication() {
    var input by remember {
        mutableStateOf("")
    }
    var message by remember {
        mutableStateOf("")
    }
    val context = LocalView.current.context
    if (message.isNotEmpty()) {
        LaunchedEffect(key1 = message) {
            messengerServer.filter { it != null }.first()!!.send(Message.obtain().apply {
                what = MessengerServer.MSG_COME
                obj = message
                replyTo = Messenger(handler)
            })

        }
    }
    DisposableEffect(true) {
        context.bindService(
            Intent(context, MessengerServer::class.java),
            connection,
            BIND_AUTO_CREATE
        )
        p = "\n开始连接"
        onDispose {
            if (messengerServer.value != null) {
                context.unbindService(connection)
            }
        }
    }
    Column {
        TextField(value = input, onValueChange = {
            input = it
        })
        Button(onClick = {
            message = input
            p += "\n发起请求:$message"
        }) {
            Text(text = "发送请求")
        }
        Text(text = "进度:")

        Text(text = p)
    }
}

var messengerServer = MutableStateFlow<Messenger?>(null)
val connection = object : ServiceConnection {
    override fun onServiceConnected(componentName: ComponentName, iBinder: IBinder) {
        p = "\n连接成功"
        messengerServer.value = Messenger(iBinder)
    }

    override fun onServiceDisconnected(componentName: ComponentName) {
        p += "\n连接断开"
    }

}